package com.mysoft.gfyx.clue.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.context.info.ContextInfo;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.sdk.system.api.MessagePush;
import com.mysoft.framework.sdk.system.dto.MessagePushDTO;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.clue.controller.dto.DeleteCustomerRequestDto;
import com.mysoft.gfyx.clue.controller.dto.EditCustomerRequestDto;
import com.mysoft.gfyx.clue.controller.dto.PubAddCustomersRequestDto;
import com.mysoft.gfyx.clue.dao.CustomerDao;
import com.mysoft.gfyx.clue.dao.CustomerHistoryDao;
import com.mysoft.gfyx.clue.dao.CustomerPoolDao;
import com.mysoft.gfyx.clue.dao.dto.RegionCustomerDataDto;
import com.mysoft.gfyx.clue.dao.dto.RegionCustomerRequestDto;
import com.mysoft.gfyx.clue.dao.entity.*;
import com.mysoft.gfyx.clue.dao.dto.CustomerDataDto;
import com.mysoft.gfyx.clue.dao.dto.CustomerRequestDto;
import com.mysoft.gfyx.clue.dao.entity.Customer;
import com.mysoft.gfyx.clue.dao.entity.CustomerHistory;
import com.mysoft.gfyx.clue.remoteservice.RemoteDeveloperService;
import com.mysoft.gfyx.clue.remoteservice.RemoteMySoftUserService;
import com.mysoft.gfyx.clue.remoteservice.dto.CreditCodeBaseRequestDto;
import com.mysoft.gfyx.clue.remoteservice.dto.RemoteUserDto;
import com.mysoft.gfyx.clue.service.*;
import com.mysoft.gfyx.clue.service.dto.*;
import com.mysoft.gfyx.common.dto.TotalDto;
import com.mysoft.gfyx.common.rpc.openapi.OpenapiClientFactoryService;
import com.mysoft.gfyx.common.rpc.openapi.OpenapiClientService;
import com.mysoft.gfyx.common.rpc.openapi.dto.*;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import groovyjarjarpicocli.CommandLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述：Customer客户管理服务 业务代码
 *
 * @author JavaSdk generator
 * @date 2022-07-07
 */
@Service
public class CustomerServiceImp extends AppService implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private CustomerPoolDao customerPoolDao;

    @Autowired
    private RemoteDeveloperService remoteDeveloperService;

    @Autowired
    private ContextManager contextManager;

    @Autowired
    private CustomerHistoryDao customerHistoryDao;

    @Autowired
    private UserBehaviourService userBehaviourService;

    @Resource
    private CustomerPoolService customerPoolService;

    @Resource
    private CustomerHistoryService customerHistoryService;

    @Resource
    private MessagePush messagePush;

    @Resource
    private OpenapiClientFactoryService openapiClientFactoryService;

    @Resource
    private RemoteMySoftUserService remoteMySoftUserService;

    @Autowired
    private MessageInboxService messageInboxService;

    @Autowired
    private NewUserService gfyxUserService;

    /**
     * 获取我的客户列表
     *
     * @param params
     * @return
     */
    public ListDataResult findCustomerList(LoadDataParams params) {
        UUID userId = contextManager.fetchContextInfo().getUserContext().getUserId();
        CustomerRequestDto dto = new CustomerRequestDto();

        dto.setUserId(userId);
        dto.setPage(params.getPageIndex() + 1);
        dto.setPageSize(params.getPageSize());
        dto.setOffset(params.getPageIndex() * dto.getPageSize());
        dto.addFilterByLoadDataApi(params.getOptions().getFilters());
        List<CustomerDataDto> list = customerDao.findCustomerList(dto);
        TotalDto total = getCustomerListTotal(dto);
        list.forEach(customer -> {
            List<String> tagsSet = new ArrayList<>();
            tagsSet.add(customer.getDeveloperTop100Label());
            tagsSet.add(customer.getIsNewAreaExpandLabel());
            tagsSet.add(customer.getIsNewLandUsageExpandLabel());
            tagsSet.add(customer.getIsNewDecorateExpandLabel());
            tagsSet.add(customer.getHighProjectCustomersLabel());
            customer.setTagsSet(tagsSet.stream().filter(item -> item != null && !item.isEmpty()).collect(Collectors.joining(",")));
            if (customer.getCustomerName() == null) {
                customer.setCustomerName("");
            }
            if (customer.getCompanyType() == null) {
                customer.setCompanyType("");
            }
            if (customer.getDeveloperActivityLabel() == null) {
                customer.setDeveloperActivityLabel("");
            }
            if (customer.getCustomerResponsiblePersonName() == null) {
                customer.setCustomerResponsiblePersonName("");
            }
            if (customer.getCooperationStatusPool() == null) {
                customer.setCooperationStatusPool("");
            }
            if (customer.getContacterCounts() == null) {
                customer.setContacterCounts(0);
            }
            if (customer.getClueCounts() == null) {
                customer.setClueCounts(0);
            }
            if (customer.getFollowTime() == null) {
                customer.setFollowTime("");
            }
            if (customer.getCustomerName() == null) {
                customer.setCustomerName("");
            }
            if (customer.getCreatedName() == null) {
                customer.setCreatedName("");
            }
        });
        ListDataResult result = new ListDataResult();
        result.setData(list);
        result.setTotal(total.getTotal());
        return result;
    }

    /**
     * 我的客户总数
     *
     * @return
     */
    public TotalDto getCustomerListTotal(CustomerRequestDto options) {
        TotalDto dto = customerDao.getCustomerListTotal(options);
        return dto;
    }

    /**
     * 我的客户列表表单字段定义
     *
     * @return
     */
    public FieldsSetting loadCustomerListFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("CustomerGUID");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "customer";

        fieldsSetting.getFields().add(new DataApiField("customerName", groupName, "客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("customerResponsiblePersonName", groupName, "负责人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contacterCounts", groupName, "联系人", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("clueCounts", groupName, "客户线索", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("createdName", groupName, "创建人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("createdTime", groupName, "创建时间", FieldType.DateTime));
        fieldsSetting.getFields().add(new DataApiField("provinceName", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("provinceCode", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryName", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryCode", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("creditCode", groupName, "统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperationStatusPool", groupName, "合作状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("followTime", groupName, "最新跟进时间", FieldType.DateTime));

        fieldsSetting.getFields().add(new DataApiField("developerActivityLabel", groupName, "活跃采购商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("companyType", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tagsSet", groupName, "企业标签", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("developerTop100Label", groupName, "地产百强标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewDecorateExpandLabel", groupName, "新精装客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewLandUsageExpandLabel", groupName, "新住宅客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewAreaExpandLabel", groupName, "新区域拓展标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("highProjectCustomersLabel", groupName, "高端项目客群标签", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    /**
     * 区域客户列表
     *
     * @param params
     * @return
     */
    public ListDataResult findRegionCustomerList(LoadDataParams params) {
        UUID userId = contextManager.fetchContextInfo().getUserContext().getUserId();
        RegionCustomerRequestDto dto = new RegionCustomerRequestDto();

        dto.setUserId(userId);
        dto.setPage(params.getPageIndex() + 1);
        dto.setPageSize(params.getPageSize());
        dto.setOffset(params.getPageIndex() * dto.getPageSize());
        dto.addFilterByLoadDataApi(params.getOptions().getFilters());
        List<RegionCustomerDataDto> list = customerDao.findRegionCustomerList(dto);
        TotalDto total = getRegionCustomerListTotal(dto);
        list.forEach(customer -> {
            List<String> tagsSet = new ArrayList<>();
            tagsSet.add(customer.getDeveloperTop100Label());
            tagsSet.add(customer.getIsNewAreaExpandLabel());
            tagsSet.add(customer.getIsNewLandUsageExpandLabel());
            tagsSet.add(customer.getIsNewDecorateExpandLabel());
            tagsSet.add(customer.getHighProjectCustomersLabel());
            customer.setTagsSet(tagsSet.stream().filter(item -> item != null && !item.isEmpty()).collect(Collectors.joining(",")));

            if (customer.getCustomerName() == null) {
                customer.setCustomerName("");
            }
            if (customer.getCompanyType() == null) {
                customer.setCompanyType("");
            }
            if (customer.getDeveloperActivityLabel() == null) {
                customer.setDeveloperActivityLabel("");
            }
            if (customer.getCustomerResponsiblePersonName() == null) {
                customer.setCustomerResponsiblePersonName("");
            }
            if (customer.getCooperationStatusPool() == null) {
                customer.setCooperationStatusPool("");
            }
            if (customer.getContacterCounts() == null) {
                customer.setContacterCounts(0);
            }
            if (customer.getClueCounts() == null) {
                customer.setClueCounts(0);
            }
            if (customer.getFollowTime() == null) {
                customer.setFollowTime("");
            }
            if (customer.getCustomerName() == null) {
                customer.setCustomerName("");
            }
            if (customer.getCreatedName() == null) {
                customer.setCreatedName("");
            }
        });
        ListDataResult result = new ListDataResult();
        result.setData(list);
        result.setTotal(total.getTotal());
        return result;
    }

    /**
     * 区域客户总数
     *
     * @return
     */
    public TotalDto getRegionCustomerListTotal(RegionCustomerRequestDto options) {
        TotalDto dto = customerDao.getRegionCustomerListTotal(options);
        return dto;
    }

    /**
     * 区域客户列表表单字段定义
     *
     * @return
     */
    public FieldsSetting loadRegionCustomerListFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("CustomerGUID");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "region_customer";

        fieldsSetting.getFields().add(new DataApiField("customerName", groupName, "客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("customerResponsiblePersonName", groupName, "负责人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("customerResponsiblePersonGUID", groupName, "负责人GUID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("contacterCounts", groupName, "联系人", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("clueCounts", groupName, "客户线索", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("createdName", groupName, "创建人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("createdTime", groupName, "创建时间", FieldType.DateTime));
        fieldsSetting.getFields().add(new DataApiField("provinceName", groupName, "省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("provinceCode", groupName, "省份Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryName", groupName, "城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("areaCategoryCode", groupName, "城市code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("creditCode", groupName, "统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("cooperationStatusPool", groupName, "合作状态", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("followTime", groupName, "最新跟进时间", FieldType.DateTime));
        fieldsSetting.getFields().add(new DataApiField("clueBUFullName", groupName, "所属组织", FieldType.String));


        fieldsSetting.getFields().add(new DataApiField("developerActivityLabel", groupName, "活跃采购商", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("companyType", groupName, "企业类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tagsSet", groupName, "企业标签", FieldType.String));

        fieldsSetting.getFields().add(new DataApiField("developerTop100Label", groupName, "地产百强标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewDecorateExpandLabel", groupName, "新精装客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewLandUsageExpandLabel", groupName, "新住宅客群标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isNewAreaExpandLabel", groupName, "新区域拓展标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("highProjectCustomersLabel", groupName, "高端项目客群标签", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    @Override
    public CustomerDto selectById(String id) {
        Customer c = customerDao.selectById(id);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerDto.class);
    }

    @Override
    public boolean flushContacterCount() {
        customerDao.flushContacterCount();
        return true;
    }

    @Override
    public int getMyCustomerCount() {
        ContextInfo contextInfo = contextManager.fetchContextInfo();
        UUID userId = contextInfo.getUserContext().getUserId();
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CustomerResponsiblePersonGUID", userId);
        queryWrapper.eq("__IsDeleted", 0);
        return customerDao.selectCount(queryWrapper).intValue();
    }

    @Override
    public CustomerDto getCustomer(Map<String, Object> conditions) {

        QueryWrapper queryWrapper = new QueryWrapper();
        conditions.forEach((key, value) -> {
            queryWrapper.eq(key, value);
        });

        queryWrapper.last("limit 1");
        Customer c = customerDao.selectOne(queryWrapper);

        return MappingUtil.getSimpleMapperFacade().map(c, CustomerDto.class);
    }

    @Override
    public Customer addCustomer(CustomerDto customerDto) {
        // 当地区没有的时候，调用接口去取地区
        if ((customerDto.getAreaCategoryCode() == null || customerDto.getAreaCategoryCode().length() == 0) || (customerDto.getProvinceCode() == null || customerDto.getProvinceCode().length() == 0)) {
            CreditCodeBaseRequestDto creditCodeBaseRequestDto = new CreditCodeBaseRequestDto();
            creditCodeBaseRequestDto.setCreditCode(customerDto.getCreditCode());
            Map<String, Object> mainData = remoteDeveloperService.getMainData(creditCodeBaseRequestDto);
            customerDto.setProvinceName(mainData.getOrDefault("province", "").toString());
            customerDto.setProvinceCode(mainData.getOrDefault("province_code", "").toString());
            customerDto.setAreaCategoryName(mainData.getOrDefault("city", "").toString());
            customerDto.setAreaCategoryCode(mainData.getOrDefault("city_code", "").toString());
        }

        // 设置客户负责人
        if (customerDto.getCustomerResponsiblePersonGUID() == null) {
            User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
            customerDto.setCustomerResponsiblePersonGUID(authenticationUser.getUserId());
            customerDto.setCustomerResponsiblePersonName(authenticationUser.getUserName());
        }

        Customer cEntity = MappingUtil.getSimpleMapperFacade().map(customerDto, Customer.class);
        customerDao.insert(cEntity);

        //发送站内信
        ArrayList<CustomerContactDto> contactList = new ArrayList<>();
        CustomerContactDto customerContactDto = new CustomerContactDto();
        customerContactDto.setCustomerResponsiblePersonGUID(customerDto.getCustomerResponsiblePersonGUID());
        customerContactDto.setCustomerResponsiblePersonName(customerDto.getCustomerResponsiblePersonName());
        contactList.add(customerContactDto);
        this.sendSiteMessage(customerDto.getBatchID(), contactList);
        return cEntity;
    }

    @Override
    public CustomerDto getCustomerWithUnique(UUID CustomerResponsiblePersonGUID, String CreditCode) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper();
        queryWrapper.eq("CustomerResponsiblePersonGUID", CustomerResponsiblePersonGUID);
        queryWrapper.eq("CreditCode", CreditCode);
        queryWrapper.eq("__IsDeleted", 0);
        queryWrapper.last("limit 1");
        Customer c = customerDao.selectOne(queryWrapper);
        return MappingUtil.getSimpleMapperFacade().map(c, CustomerDto.class);
    }

    public List<Customer> getCustomersByCreditCode(String creditCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CreditCode", creditCode);
        queryWrapper.eq("__IsDeleted", 0);
        return customerDao.selectList(queryWrapper);
    }

    @Override
    public boolean addCustomers(Collection<CustomerDto> customersDto) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        Collection<String> creditCodes = new ArrayList<>();
        customersDto.forEach(c -> {
            c.setCustomerResponsiblePersonGUID(authenticationUser.getUserId());
            c.setCustomerResponsiblePersonName(authenticationUser.getUserName());
            creditCodes.add(c.getCreditCode());
        });

        if (creditCodes.size() == 0) {
            throw new BusinessLogicException("您尚未选择客户");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CustomerResponsiblePersonGUID", authenticationUser.getUserId());
        queryWrapper.in("CreditCode", creditCodes);
        queryWrapper.eq("__IsDeleted", 0);
        List<Customer> exits = customerDao.selectList(queryWrapper);
        Set<String> exitsCreditCode = new HashSet<>();
        exits.forEach(e -> {
            exitsCreditCode.add(e.getCreditCode());
        });

        Collection<Customer> customers = new ArrayList<>();
        customersDto.forEach(c -> {
            if (!exitsCreditCode.contains(c.getCreditCode())) {
                customers.add(MappingUtil.getSimpleMapperFacade().map(c, Customer.class));
            }

        });
        if (customers.size() > 0) {
            customerDao.insertBatchWithDynamicExt(customers);
        }

        return true;
    }

    @Override
    public boolean batchCustomersAndHistory(PubAddCustomersRequestDto pubAddCustomersDto) {
        UUID BatchId = UUID.randomUUID();//批次ID
        List<CustomerDto> customerList = pubAddCustomersDto.getCustomers();
        List<CustomerContactDto> contacts = pubAddCustomersDto.getContact();
        Collection<String> creditCodes = new ArrayList<>();
        customerList.forEach(customerRow -> {
            creditCodes.add(customerRow.getCreditCode());

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("CreditCode", customerRow.getCreditCode());
            queryWrapper.eq("__IsDeleted", 0);
            List<Customer> exits = customerDao.selectList(queryWrapper);
            Set<UUID> exitsContactID = new HashSet<>();
            exits.forEach(e -> {
                exitsContactID.add(e.getCustomerResponsiblePersonGUID());
            });

            Collection<Customer> customers = new ArrayList<>();
            Collection<CustomerHistory> customerHistorys = new ArrayList<>();
            Set<UUID> contactID = new HashSet<>();
            contacts.forEach(contactRow -> {//循环负责人
                if (!exitsContactID.contains(contactRow.getCustomerResponsiblePersonGUID())) {
                    //customer表
                    customerRow.setCustomerResponsiblePersonGUID(contactRow.getCustomerResponsiblePersonGUID());
                    customerRow.setCustomerResponsiblePersonName(contactRow.getCustomerResponsiblePersonName());
                    customerRow.setBatchID(BatchId);
                    customerRow.setCustomerGUID(UUID.randomUUID());

                    Map<String, Object> conditions = new HashMap<>();
                    conditions.put("CreditCode", customerRow.getCreditCode());
                    conditions.put("__IsDeleted", 0);
                    CustomerPoolDto customerPoolDto = customerPoolService.getCustomerPool(conditions);
                    customerRow.setCustomerPoolGUID(customerPoolDto.getCustomerPoolGUID());
                    customers.add(MappingUtil.getSimpleMapperFacade().map(customerRow, Customer.class));
                    //customerHistory表
                    QueryWrapper<CustomerHistory> queryWrapperHis = new QueryWrapper<>();
                    queryWrapperHis.eq("CustomerResponsiblePersonGUID", customerRow.getCustomerResponsiblePersonGUID().toString());
                    queryWrapperHis.eq("CreditCode", customerRow.getCreditCode());
                    Integer customerHistoryCount = customerHistoryDao.selectCount(queryWrapperHis).intValue();
                    if (customerHistoryCount.equals(0)) {
                        customerHistorys.add(MappingUtil.getSimpleMapperFacade().map(customerRow, CustomerHistory.class));
                    }
                }
                contactID.add(contactRow.getCustomerResponsiblePersonGUID());
            });
            if (customers.size() > 0) {
                customerDao.insertBatchWithDynamicExt(customers);
            } else if (pubAddCustomersDto.getIsBatch().equals(CustomerService.Single_ADD) && pubAddCustomersDto.getOperation().equals(CustomerService.OPERATION_ADD) && pubAddCustomersDto.getCustomers().size() == 1) {
                throw new BusinessLogicException("您已添加该客户");
            }

            if (customerHistorys.size() > 0) {
                customerHistoryDao.insertBatchWithDynamicExt(customerHistorys);
            }

            //批量：增量添加负责人
            //单个：增量添加负责人外，还需删除不存在的负责人
            if (pubAddCustomersDto.getIsBatch().equals(CustomerService.Single_ADD) && pubAddCustomersDto.getOperation().equals(CustomerService.OPERATION_EDIT)) {
                List<String> deleteContactID = new ArrayList<>();
                exitsContactID.forEach(e -> {
                    if (!contactID.contains(e)) {
                        deleteContactID.add(e.toString());
                    }
                });
                if (deleteContactID.size() > 0) {
                    QueryWrapper<Customer> deleteWrapper = new QueryWrapper<>();
                    deleteWrapper.in("CustomerResponsiblePersonGUID", deleteContactID);
                    deleteWrapper.eq("CreditCode", customerRow.getCreditCode());

                    Customer updateData = new Customer();
                    updateData.set__IsDeleted(1);
                    customerDao.update(updateData, deleteWrapper);
                }
            }

        });

        if (pubAddCustomersDto.getCustomers().size() > 0) {
            this.sendSiteMessage(BatchId, pubAddCustomersDto.getContact());
        }
        return true;
    }

    private boolean importCustomers(List<CustomerPoolDto> customerPoolDtoList) {
        UUID BatchId = UUID.randomUUID();//批次ID
        List<String> companyNameList = new ArrayList<>();
        customerPoolDtoList.forEach(customerRow -> {
            companyNameList.add(customerRow.getCustomerName());
        });
        // 查询所有的客户列表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("CustomerName", companyNameList);
        queryWrapper.eq("__IsDeleted", 0);
        List<Customer> exits = customerDao.selectList(queryWrapper);
        // 插入新的负责人
        List<Customer> customerList = new ArrayList<>();
        customerPoolDtoList.forEach(customerPoolDto -> {
            // 如果客户负责人存在则不处理
            if (customerPoolDto.getCustomerResponsiblePersonGUID() != null) {
                Customer customer = new Customer();
                boolean isSave = true;
                for (Customer e : exits) {
                    // 如果存在这条数据，且这条数据的负责人不是它，那就是新增，否则就不处理
                    if (Objects.equals(e.getCustomerName(), customerPoolDto.getCustomerName()) && e.getCustomerResponsiblePersonGUID().equals(customerPoolDto.getCustomerResponsiblePersonGUID())) {
                        isSave = false;
                        break;
                    }
                }
                // 如果都不存在，则证明是新增
                if (isSave) {
                    customer.setCustomerName(customerPoolDto.getCustomerName());
                    customer.setCustomerPoolGUID(customerPoolDto.getCustomerPoolGUID());
                    customer.setCooperationStatus(customerPoolDto.getCooperationStatus());
                    customer.setAreaCategoryCode(customerPoolDto.getAreaCategoryCode());
                    customer.setAreaCategoryName(customerPoolDto.getAreaCategoryName());
                    customer.setProvinceCode(customerPoolDto.getProvinceCode());
                    customer.setProvinceName(customerPoolDto.getProvinceName());
                    customer.setCreditCode(customerPoolDto.getCreditCode());
                    customer.setCustomerResponsiblePersonGUID(customerPoolDto.getCustomerResponsiblePersonGUID());
                    customer.setCustomerResponsiblePersonName(customerPoolDto.getCustomerResponsiblePersonName());
                    customer.setBatchID(BatchId);
                    customerList.add(customer);
                }
            }
        });

        // 插入逻辑处理
        if (customerList.size() > 0) {
            // 插入
            customerDao.insertBatchWithDynamicExt(customerList);
        }

        return true;
    }

    @Override
    public boolean sendSiteMessage(UUID batchId, ArrayList<CustomerContactDto> contactList) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        // 站内信
        contactList.forEach(e -> {
            UUID userId = e.getCustomerResponsiblePersonGUID();
            //获取添加的客户
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("BatchId", batchId);
            queryWrapper.in("CustomerResponsiblePersonGUID", e.getCustomerResponsiblePersonGUID());
            List<Customer> customerList = customerDao.selectList(queryWrapper);
            if (customerList.size() > 0) {
                MessagePushDTO dto = new MessagePushDTO();
                dto.setUserGuid(userId);
                dto.setWakeType("普通消息");
                dto.setWakeSubject("尊敬的用户，贵司【" + authenticationUser.getUserName() + "】为您分配了" + customerList.size() + "家客户，请及时查阅，立即查看。");
                dto.setAppCode("4022");
                dto.setPageUrl("/std/40220902/08daf483-0f12-45a2-828e-f4b066fa28f7");//跳转客户管理=>我的客户页面
                dto.setBusinessGuid(UUID.randomUUID());
                dto.setBusinessType("客户分配");
                messagePush.sendToDo(dto);

                MessageInboxDto messageDto = new MessageInboxDto();
                messageDto.setTitle("新增客户通知");
                messageDto.setMessageType("客户分配");
                messageDto.setContent(dto.getWakeSubject());
                messageDto.setLink(dto.getPageUrl());
                messageDto.setSenderId(gfyxUserService.GetAdminId());
                messageDto.setReceiverId(gfyxUserService.GetUserId(userId.toString()));
                messageInboxService.AddMessage(messageDto);
            }

        });

        return true;

    }

    @Override
    @Transactional
    public boolean addCustomerAndPool(PubAddCustomersRequestDto req) {
        this.checkAddCustomer(req);
        // 写入客户池
        Collection<CustomerDto> customerList = req.getCustomers();
        Collection<CustomerPoolDto> customerPoolList = new ArrayList<>();
        List<String> creditCodeList = new ArrayList<>();
        customerList.forEach(c -> {
            CustomerPoolDto customerPoolDto = MappingUtil.getSimpleMapperFacade().map(c, CustomerPoolDto.class);
            customerPoolDto.setCooperationStatus(req.getCooperationStatus());
            if (req.getAction().equals(CustomerService.ACTION_CUSTOMER) && req.getContact().size() > 0) {
                customerPoolDto.setAssignStatus(CustomerPoolService.ASSIGN_STATUS_HAS);
            } else {
                customerPoolDto.setAssignStatus(CustomerPoolService.ASSIGN_STATUS_NEVER);
            }
            customerPoolList.add(customerPoolDto);
            creditCodeList.add(c.getCreditCode());
        });

        customerPoolService.addCustomerPools(customerPoolList);
        //写入客户、客户历史记录
        if (req.getAction().equals(CustomerService.ACTION_CUSTOMER)) {
            this.batchCustomersAndHistory(req);//支持单个/批量添加客户
        }

        customerPoolDao.updateAssignStatus(creditCodeList);
        return true;
    }

    private void checkAddCustomer(PubAddCustomersRequestDto req) {
        if (req.getCustomers().size() <= 0) {
            throw new BusinessLogicException("你尚未选择客户");
        }
        req.getCustomers().forEach(r -> {
            if (r.getCreditCode() == null || r.getCreditCode().toString().length() == 0) {
                throw new BusinessLogicException("存在信用代码为空的企业");
            }
        });

    }

    @Override
    public boolean editCustomerAndPool(EditCustomerRequestDto req) {
        if (req.getCustomerGUID() == null) {
            throw new BusinessLogicException("你尚未选择客户");
        }
        Customer customer = customerDao.selectById(req.getCustomerGUID());
        if (customer != null) {
            Map<String, Object> conditionsCustomer = new HashMap<>();
            conditionsCustomer.put("CustomerResponsiblePersonGUID", req.getCustomerResponsiblePersonGUID().toString());
            conditionsCustomer.put("CreditCode", customer.getCreditCode());
            conditionsCustomer.put("__IsDeleted", 0);
            CustomerDto isExist = this.getCustomer(conditionsCustomer);
            if (isExist != null && !isExist.getCustomerGUID().equals(req.getCustomerGUID())) {
                throw new BusinessLogicException("用户【" + req.getCustomerResponsiblePersonName() + "】已经是负责人，无法重复添加");
            }
            //写入客户
            customer.setCustomerResponsiblePersonGUID(req.getCustomerResponsiblePersonGUID());
            customer.setCustomerResponsiblePersonName(req.getCustomerResponsiblePersonName());
            customerDao.updateById(customer);

            //客户历史记录
            QueryWrapper<CustomerHistory> queryWrapperHis = new QueryWrapper<>();
            queryWrapperHis.eq("CustomerGUID", req.getCustomerGUID().toString());
            queryWrapperHis.last("limit 1");
            CustomerHistory customerPoolHistory = customerHistoryDao.selectOne(queryWrapperHis);
            if (customerPoolHistory != null) {
                customerPoolHistory = MappingUtil.getSimpleMapperFacade().map(customer, CustomerHistory.class);
                customerHistoryDao.updateById(customerPoolHistory);
            }
            //写入客户池
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("CreditCode", customer.getCreditCode());
            conditions.put("__IsDeleted", 0);
            CustomerPoolDto customerPoolDto = customerPoolService.getCustomerPool(conditions);
            if (customerPoolDto == null) {
                customerPoolDto = MappingUtil.getSimpleMapperFacade().map(customer, CustomerPoolDto.class);
                customerPoolDto.setCooperationStatus(req.getCooperationStatus());
                customerPoolDto.setAssignStatus(CustomerPoolService.ASSIGN_STATUS_HAS);
                customerPoolService.addCustomerPool(customerPoolDto);
            } else {
                customerPoolDto.setCooperationStatus(req.getCooperationStatus());
                customerPoolService.editCustomerPool(customerPoolDto);
            }

        }
        return true;
    }

    public void deleteCustomer(DeleteCustomerRequestDto dto) {
        // 首先确认这段关系……
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customerGUID", dto.getCustomerGUID());
        queryWrapper.eq("__IsDeleted", 0);
        queryWrapper.last("limit 1");
        Customer customer = customerDao.selectOne(queryWrapper);
        String creditCode = customer.getCreditCode();
        UUID userGUID = customer.getCustomerResponsiblePersonGUID();
        String customerName = customer.getCustomerName();

        // 然后删除这段关系……
        customer.set__IsDeleted(1);
        customerDao.updateById(customer);

        // 然后查看是否还有其它客户负责它
        List<Customer> customers = getCustomersByCreditCode(creditCode);
        if (customers == null || customers.size() == 0) {
            QueryWrapper<CustomerPool> customerPoolQueryWrapper = new QueryWrapper<>();
            customerPoolQueryWrapper.eq("CreditCode", creditCode);
            customerPoolQueryWrapper.eq("__IsDeleted", 0);
            customerPoolQueryWrapper.last("limit 1");
            CustomerPool customerPool = customerPoolDao.selectOne(customerPoolQueryWrapper);
            customerPool.setAssignStatus("0");
            customerPoolDao.updateById(customerPool);
        }

        // 发站内信
        MessagePushDTO messagePushDTO = new MessagePushDTO();
        messagePushDTO.setUserGuid(userGUID);
        messagePushDTO.setWakeType("普通消息");
        messagePushDTO.setWakeSubject("尊敬的用户，您负责的客户【" + customerName + "】已被删除。");
        messagePushDTO.setAppCode("4022");
        messagePushDTO.setPageUrl("/std/40220902/08daf483-0f12-45a2-828e-f4b066fa28f7");
        messagePushDTO.setBusinessGuid(UUID.randomUUID());
        messagePushDTO.setBusinessType("客户变动");
        messagePush.sendToDo(messagePushDTO);

        //用户操作日志
        userBehaviourService.addUserBehaviour("客户管理", "", "删除客户", "删除了客户【" + customer.getCustomerName() + "】");
    }

    public Set<String> isAdded(List<String> creditCodes) {
        if (creditCodes == null || creditCodes.size() == 0) {
            return new HashSet<>();
        }
        UUID userUUID = contextManager.fetchContextInfo().getUserContext().getUserId();

        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customerResponsiblePersonGUID", userUUID);
        queryWrapper.in("CreditCode", creditCodes);
        queryWrapper.eq("__IsDeleted", 0);

        List<Customer> clues = customerDao.selectList(queryWrapper);
        Set<String> addedList = new HashSet<>();

        clues.forEach(c -> {
            addedList.add(c.getCreditCode());
        });

        return addedList;
    }

    public List<Map<String, Object>> exportCustomer(LoadDataParams options) {
        if (options.getPageIndex() == -1) {
            options.setPageIndex(0);
            // 因为数芯最多就支持2000，所以没必要更多了
            options.setPageSize(2000);
        }
        return (List<Map<String, Object>>) findCustomerList(options).getData();
    }

    public List<Map<String, Object>> exportRegionCustomer(LoadDataParams options) {
        if (options.getPageIndex() == -1) {
            options.setPageIndex(0);
            // 因为数芯最多就支持2000，所以没必要更多了
            options.setPageSize(2000);
        }
        return (List<Map<String, Object>>) findRegionCustomerList(options).getData();
    }

    /**
     * 批量导入客户数据
     * 1 避免客户，客户池出现重复数据
     * 2. 加入客户池，按照合作状态，如果过负责人不在系统，则只进入客户池
     * 3, 如果负责人在系统里，则添加到对应的客户
     * 4, 记录操作日志
     * 5, 更新数据时，刷新标签
     */
    public List<String> importCustomerPool(String path) throws IOException {
        // 读取 excel 内容
        URL url = new URL(path);
        InputStream in = url.openStream();
        List<ImportCustomerPoolDto> importData = EasyExcel.read(in).head(ImportCustomerPoolDto.class).sheet().doReadSync();
        in.close();

        List<String> errorCompanyList = new ArrayList<String>();
        List<String> companyNameList = new ArrayList<>();
        PubAddCustomersRequestDto addCustomersRequestDto = new PubAddCustomersRequestDto();
        List<CustomerPoolDto> customerPoolList = new ArrayList<>();
        List<ApplyMainDataReqDto.Developers> applyList = new ArrayList<ApplyMainDataReqDto.Developers>();
        OpenapiClientService openapiClientService = openapiClientFactoryService.getOpenapiService();

        // 获取建模用户数据，由于 mip 限制一定要传参数，不然会报错，所以传了无效的字符
        List<RemoteUserDto> userDtoList = remoteMySoftUserService.GetAllUsers("u");
        List<String> userNameList = new ArrayList<>();
        for (RemoteUserDto userDto : userDtoList) {
            userNameList.add(userDto.getUserName());
        }

        // 获取主档案数据，补充内容
        for (ImportCustomerPoolDto importItem : importData) {
            companyNameList.add(importItem.getCustomerName());
        }
        GetMainDataReqDto mainReqDto = new GetMainDataReqDto();
        mainReqDto.setDeveloper(companyNameList);
        GetMainDataRespDto mainDataResp = openapiClientService.getMainDataByCompanyName(mainReqDto);

        // 收集 excel 的数据转换成对象
        for (ImportCustomerPoolDto importItem : importData) {
            if (Objects.equals(importItem.getCustomerName(), "") || importItem.getCustomerName() == null) {
                continue;
            }
            CustomerPoolDto customerPoolDto = new CustomerPoolDto();
            customerPoolDto.setCustomerName(importItem.getCustomerName());
            customerPoolDto.setSource("import");
            // 设置合作状态
            switch (importItem.getCooperationStatus()) {
                case "未合作":
                    customerPoolDto.setCooperationStatus(CustomerService.COOPERATION_STATUS_NEVER);
                    break;
                case "已合作":
                    customerPoolDto.setCooperationStatus(CustomerService.COOPERATION_STATUS_KNOWN);
                    break;
                case "已入库":
                    customerPoolDto.setCooperationStatus(CustomerService.COOPERATION_STATUS_STOCK);
                    break;
            }
            // 设置招标负责人，如果招标负责人为空，且不存在系统，并且不添加到我的客户
            if (!importItem.getCustomerResponsiblePerson().isEmpty() && userNameList.contains(importItem.getCustomerResponsiblePerson())) {
                customerPoolDto.setAssignStatus(CustomerPoolService.ASSIGN_STATUS_HAS);
            } else {
                customerPoolDto.setAssignStatus(CustomerPoolService.ASSIGN_STATUS_NEVER);
            }
            // 根据主档案补充信用代码以及省份信息
            for (MainDataDto mainDataDto : mainDataResp.getData()) {
                if (Objects.equals(importItem.getCustomerName(), mainDataDto.getName())) {
                    customerPoolDto.setCreditCode(mainDataDto.getCredit_code());
                    customerPoolDto.setAreaCategoryCode(mainDataDto.getCity_code());
                    customerPoolDto.setAreaCategoryName(mainDataDto.getCity());
                    customerPoolDto.setProvinceCode(mainDataDto.getProvince_code());
                    customerPoolDto.setProvinceName(mainDataDto.getProvince());
                    break;
                }
            }
            // 根据名称补充负责人名称和id
            for (RemoteUserDto user : userDtoList) {
                if (Objects.equals(user.getUserName(), importItem.getCustomerResponsiblePerson())) {
                    customerPoolDto.setCustomerResponsiblePersonName(user.getUserName());
                    customerPoolDto.setCustomerResponsiblePersonGUID(user.getUserGUID());
                }
            }

            customerPoolList.add(customerPoolDto);
        }

        // 添加到客户池
        customerPoolList = customerPoolService.addCustomerPoolsByName(customerPoolList);

        // 添加客户
        this.importCustomers(customerPoolList);

        // 不存在主档案则添加反哺任务
        for (CustomerPoolDto customerPoolDto : customerPoolList) {
            if (Objects.equals(customerPoolDto.getCreditCode(), "") || customerPoolDto.getCreditCode() == null) {
                ApplyMainDataReqDto.Developers company = new ApplyMainDataReqDto.Developers();
                company.setCompany_name(customerPoolDto.getCustomerName());
                company.setSource("5");
                company.setSource_id("");
                applyList.add(company);
            }
        }

        try {
            ApplyMainDataReqDto applyMainDataReqDto = new ApplyMainDataReqDto();
            applyMainDataReqDto.setType("kfs");
            applyMainDataReqDto.setData(applyList);
            openapiClientService.applyDeveloperMainData(applyMainDataReqDto);
            return errorCompanyList;
        } catch (Exception e) {
            return errorCompanyList;
        }
    }
}